<?php

namespace common\traits;

use Yii;
use yii\data\ActiveDataProvider;

/**
 * Description of Constants
 *
 * @author emhome
 */
trait SearchForBuildQuery {

    /**
     * @var integer 分页请求大小
     */
    public $pagesize = 20;

    /**
     * @var integer 分页请求大小
     */
    public $limitSize = false;

    /**
     * @var integer 查询缓存时间
     */
    public $queryCacheDuration = false;

    /**
     * 条件检索
     * @param mixed $params 缓存时间
     * @return ActiveDataProvider
     */
    public function search($params = []) {
        $query = null;
        $method = 'buildQuery';
        $handler = array($this, $method);
        if ($this->hasMethod($method) && is_callable($handler)) {
            if (!empty($params)) {
                $this->load($params, '');
            }
            $query = call_user_func_array($handler, []);
        } else {
            $query = static::find();
        }
        if ($this->pagesize === false) {
            if ($this->limitSize !== false) {
                $query->limit($this->limitSize);
            }
            return $query->all();
        }
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'validatePage' => false,
                'pageSize' => $this->pagesize,
            ],
        ]);
        if (!YII_DEBUG && $this->queryCacheDuration !== false) {
            Yii::$app->db->cache(function($db) use($dataProvider) {
                $dataProvider->prepare();
            }, $this->queryCacheDuration);
        }
        return $dataProvider;
    }

}
